#include "mymapcanvas.h"

#include <qgslinestring.h>
#include <qgsmapcanvasitem.h>
#include <qgsvectorlayer.h>

MyMapCanvas::MyMapCanvas() {
   coordItem = new TextQgsMapCanvasItem(this);
   // annotationLayer = new QgsAnnotationLayer("Annotations", QgsAnnotationLayer::LayerOptions(QgsProject::instance()->transformContext()));
   // QgsProject::instance()->addMapLayer(annotationLayer);
   textItem = new QgsAnnotationPointTextItem("", QgsPointXY(0,0));
   // annotationLayer->addItem(textItem);
   // setLayers(QList<QgsMapLayer *>() << annotationLayer);
}

void MyMapCanvas::addTraceLine(QgsPointXY &point)
{
    // 获取当前项目
    QgsProject* project = QgsProject::instance();
    QgsVectorLayer* vectorLayer = (QgsVectorLayer*)project->mapLayersByName("LineLayer").value(0);

    if (vectorLayer == NULL || !vectorLayer->isValid()) {
        qDebug() << " no line vector layer";
        return;
    }
    QgsLineString *lineString = new QgsLineString();

    lineString->addVertex(QgsPoint(lastPoint.x(), lastPoint.y()));
    lineString->addVertex(QgsPoint(point.x(), point.y()));

    QgsFeature feature;
    feature.setGeometry(QgsGeometry(lineString));

    QgsFeatureList features;
    features << feature;
    vectorLayer->dataProvider()->addFeatures(features);
    vectorLayer->updateExtents();
    this->refresh();

    setLastPoint(point);
}

void MyMapCanvas::addTracePoint(QgsPointXY &point)
{
    // 获取当前项目
    QgsProject* project = QgsProject::instance();
    QgsVectorLayer* vectorLayer = (QgsVectorLayer*)project->mapLayersByName("PointLayer").value(0);
    if (vectorLayer == NULL || !vectorLayer->isValid()) {
        qDebug() << " no line vector layer";
        return;
    }

    QgsFeature feature;
    feature.setFields(vectorLayer->fields());
    feature.setAttribute("id", id++);

    QgsFeatureList features;

    feature.setGeometry(QgsGeometry::fromPointXY(point));
    vectorLayer->dataProvider()->addFeature(feature);
    vectorLayer->updateExtents();

}

QgsPointXY MyMapCanvas::getLastPoint() const
{
    return lastPoint;
}

void MyMapCanvas::setLastPoint(QgsPointXY newLastPoint)
{
    lastPoint = newLastPoint;
}

void MyMapCanvas::setAnnotationLayer(QgsAnnotationLayer *newAnnotationLayer)
{
    annotationLayer = newAnnotationLayer;
    annotationLayer->addItem(textItem);
}
